package com.ptu.service.impl;


import com.ptu.entity.Expense;
import com.ptu.entity.ExpenseItem;
import com.ptu.mapper.ExpImageMapper;
import com.ptu.mapper.ExpenseItemMapper;
import com.ptu.mapper.ExpenseMapper;
import com.ptu.service.ExpenseService;
import com.ptu.util.DBUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class ExpenseServiceImpl  implements ExpenseService {

    @Override
    public int add(Expense expense, List<ExpenseItem> list) {
        SqlSession sqlSession = DBUtil.getSqlSession();
        ExpenseMapper mapper = sqlSession.getMapper(ExpenseMapper.class);
        ExpenseItemMapper mapper1 = sqlSession.getMapper(ExpenseItemMapper.class);

        int i = 0;

        try {
            //报销单添加
            mapper.insert(expense);

            //报销单明细添加
            for(ExpenseItem  item:list){

                item.setExpId(expense.getExpId());

                mapper1.insert(item);
            }

            i=1;
        } catch (Exception e) {

            sqlSession.rollback();

        } finally {
            DBUtil.closeAll();
        }

        return i;
    }

    @Override
    public List<Expense> findExpenseMore(String next) {

        ExpenseMapper mapper = DBUtil.getSqlSession().getMapper(ExpenseMapper.class);
        List<Expense> expenses = mapper.selectMore(next, "0");
        DBUtil.closeAll();

        return expenses;
    }

    @Override
    public List<Expense> findMyExpense(String empId) {

        ExpenseMapper mapper = DBUtil.getSqlSession().getMapper(ExpenseMapper.class);
        List<Expense> expenses = mapper.selectMyExp(empId);
        DBUtil.closeAll();

        return expenses;
    }

    @Override
    public int removeExp(int expId) {
        SqlSession sqlSession = DBUtil.getSqlSession();
        ExpenseMapper mapper = sqlSession.getMapper(ExpenseMapper.class);
        ExpenseItemMapper mapper1 = sqlSession.getMapper(ExpenseItemMapper.class);
        ExpImageMapper mapper2 = sqlSession.getMapper(ExpImageMapper.class);

        int i=0;
        try {
            // 报销单明细删除
            mapper1.delExpItem(expId);
            mapper2.delImage(expId);
            mapper.delExp(expId);

            i=1;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeAll();
        }

        return i;
    }


}
